/**
 * @description 商品详情
 */
import style from './styles/Pay.less';
import classnames from "classnames";
import React from 'react';
const Fragment = React.Fragment;
import { Button, List, ListItem, Icon, Dialog, Toast, Switch, Popup } from 'wd-mobile';
import { pay } from "api_zhoujianyi/front/app/payment";
import { page as pageDetail } from "api_zhoujianyi/front/app/trade/pay";
import { detail } from "api_liuhaojie/app/goods";
import { list } from "api_zhoujianyi/front/app/trade/coupon";
import { query_user_beans, bean_rule } from "api_xukaiyu/app/beans";
import { purchase } from "api_zhoujianyi/front/app/trade";


import device from "commons/device";
import wxShare from "commons/wxShare";
import util from "commons/util";


import icon_wechat from "images/icon/wechat.png";
import icon_coin from "images/icon/coin.png";
import icon_redpacket from "images/icon/redpacket.png";

const queryObject = util.parseQueryString();

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            countNum: 1, // 购买量
            detail: {},
            accountType: "WECHAT", // 支付类型
            buyTimeFormateText: "", // 购买倒计时格式化时间
            hasDeduction: false,// 是否使用嗨豆
            visible: false,// 红包选择
            redList: [],//可选红包列表
            redIndex: 0,
            allBeans: 0,//嗨豆数目
            noNeedPay: true,
            tradeNo: "",
            beanRule: {
                minUse: 0,
                proportion: 1,
                maxUse: 0
            },
            // account:''
        }

        this.stateTimmer = null; // 查询支付状态定时器；
        this.stateTimes = 0; // 查询支付状态次数

        // 倒计时
        this.buyTime = 5; // 购买倒计时，分钟
        this.futureTime = 0// 固定的未来时间
    }

    // 计算购买倒计时
    runBuyTime() {
        let currentTime = new Date().getTime();// 当前时间戳
        let timediff = util.Sub(this.futureTime, currentTime);// 毫秒数差
        let secdiff = util.Div(timediff, 1000);// 秒数差;
        let secText = secdiff % 60;// 秒位数
        let minText = parseInt(util.Div(secdiff, 60));
        secText = Math.floor(secText);
        minText = Math.floor(minText);
        if (secText <= 0 && minText <= 0) {
            this.setState({
                buyTimeFormateText: "00:00"
            })
            return true;
        }
        this.setState({
            buyTimeFormateText: (minText < 10 ? "0" + minText : minText) + ":" + (secText < 10 ? "0" + secText : secText)
        })

        return false;
    }

    componentDidMount() {
        const _this = this;
        //嗨豆数量
        query_user_beans().then(data => {
            this.setState({
                allBeans: data.data || 0
            })
        })

        //嗨豆比例
        bean_rule().then(data => {
            this.setState({
                beanRule: data.data
            })
        })
        if (queryObject.purchase) {
            detail({
                skuId: this.props.match.params.tradeNo
            }).then(res => {
                list({ tradeAmount: res.data.price * queryObject.purchase, goodsType: res.data.id }).then(conpon => {
                    this.setState({
                        redList: conpon.data,
                        detail: {
                            ...res.data,
                            goodsTypeName: res.data.skuName,
                            goodsPrice: res.data.price,
                            goodsDiscountAmount: util.Sub(res.data.recommendPrice || 0, res.data.price || 0),
                            quantity: queryObject.purchase,
                            tradeAmount: util.Mul(queryObject.purchase, res.data.price || 0)
                        }
                    })
                })
                // 设置分享到商品
                let shareData = {};
                let pathNameArr = location.pathname.split("/");
                pathNameArr.pop();
                shareData.link = location.origin + pathNameArr.join("/") + "/goods.html" + `#/Detail/${res.data.id}`;
                shareData.title = `在吗？给你推荐${res.data.skuName}`;
                shareData.desc = `${res.data.skuName}已售${res.data.soldNum}件，库存不多，悄悄分享给你`;
                shareData.imgUrl = res.data.goodsIcon;
                wxShare(shareData);
            })
        } else {
            // 交易详情
            pageDetail({
                tradeNo: this.props.match.params.tradeNo
            }).then(res => {
                this.setState({
                    detail: res.data,
                    noNeedPay: false
                }, () => {
                    this.futureTime = new Date(this.state.detail.gmtCreated.replace(/-/g, "/")).getTime() + this.buyTime * 60 * 1000; // 固定的未来时间
                    if (!!this.runBuyTime()) {
                        Dialog.alert("库存可能发生变动，请重新下单。", "订单超时", () => {
                            history.back();
                        })
                    } else {
                        this.buyTimmer = setInterval(() => {
                            if (!!this.runBuyTime()) {
                                clearInterval(this.buyTimmer);
                                Dialog.alert("库存可能发生变动，请重新下单。", "订单超时", () => {
                                    history.back();
                                })
                            }
                        }, 1000)
                    }
                })

                return res.data;
            }).then((data) => {
                detail({
                    skuId: data.goodsType
                }).then(res => {
                    list({ tradeAmount: data.tradeAmount, goodsType: res.data.id }).then(conpon => {
                        this.setState({
                            redList: conpon.data,
                        })
                    })
                    // 设置分享到商品
                    let shareData = {};
                    let pathNameArr = location.pathname.split("/");
                    pathNameArr.pop();
                    shareData.link = location.origin + pathNameArr.join("/") + "/goods.html" + `#/Detail/${res.data.id}`;
                    shareData.title = `在吗？给你推荐${res.data.skuName}`;
                    shareData.desc = `${res.data.skuName}已售${res.data.soldNum}件，库存不多，悄悄分享给你`;
                    shareData.imgUrl = res.data.goodsIcon;
                    wxShare(shareData);
                })
            })
        }
    }

    //支付
    payMoney(tradeNo, neeDHaiDouMoney) {
        pay({
            tradeNo: tradeNo,
            amount: neeDHaiDouMoney,
            origin: !!util.isWeixin() ? "JSAPI" : "H5",
            accountType: this.state.accountType,
            terminalSystemType: device.android() ? "ANDROID" : "IOS",
            terminalIp: returnCitySN["cip"],////pv.sohu.com/cityjson?ie=utf-8
        }).then(res => {
            Toast.destroy();
            const thisTradeNo = tradeNo;
            if (res.data.origin == "H5") {
                location.href = `./toPayInWechat.html?payUrl=${encodeURIComponent(res.message)}&tradeNo=${thisTradeNo}`;
            }
            if (res.data.origin == "JSAPI") {
                const jssdkPayConfig = JSON.parse(res.data.remark);
                jssdkPayConfig.paySign = jssdkPayConfig.sign;
                WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', jssdkPayConfig,
                    function (wdres) {
                        if (wdres.err_msg == "get_brand_wcpay_request:ok") {
                            location.replace(`./goods.html#PayResult/${thisTradeNo}`);
                        }
                    });
            }
        })
    }

    render() {
        const { hasDeduction, redList, redIndex, allBeans, detail, beanRule, noNeedPay } = this.state;
        let canUseBeans = 0;//可用黑豆
        let noBeansMoney = 0;
        let neeDHaiDouMoney = util.Sub(detail.tradeAmount || 0, (redIndex != -1) && redList[redIndex] ? (redList[redIndex].calculateActualAmount || 0) : 0);//抵扣红包计算
        
        noBeansMoney = neeDHaiDouMoney;
        if (allBeans >= beanRule.minUse) {
            if (allBeans <= Math.floor(util.Mul(neeDHaiDouMoney, beanRule.proportion))) {
                if (allBeans >= beanRule.maxUse) {
                    canUseBeans = beanRule.maxUse
                } else {
                    canUseBeans = allBeans;
                }
            } else {
                canUseBeans = Math.floor(util.Mul(neeDHaiDouMoney, beanRule.proportion));
                if (canUseBeans >= beanRule.maxUse && (beanRule.maxUse != -1)) {
                    canUseBeans = beanRule.maxUse;
                }
            }
        } else {
            canUseBeans = 0;
        }

        if (hasDeduction && noBeansMoney != '0.01') {
            neeDHaiDouMoney = util.Sub(neeDHaiDouMoney, canUseBeans / 100);
        }
        if (!noNeedPay) {
            neeDHaiDouMoney = util.Sub(neeDHaiDouMoney, detail.pointAmount);
        }
        let { tradeNo } = this.props.match.params;

        return (
            <Fragment>
                <div className={classnames(style.main, "x-scroll-y")}>
                    <List renderHeader={<span>商品信息</span>}>
                        <div className={style.orderInfo}>
                            <div className={classnames(style.orderNo, "x-part")} hidden={queryObject.purchase}><span>交易号：{tradeNo}</span></div>
                            <div className={classnames(style.orderInfoGoods, "x-part")}>
                                <div className={style.orderInfoGoodsImg}>
                                    <div className={style.orderInfoGoodsImgContainer} style={detail.goodsIcon ? { backgroundImage: `url(${detail.goodsIcon})` } : null}></div>
                                </div>
                                <div className={style.orderInfoGoodsText}>
                                    <div className={style.orderInfoGoodsTitle}><span>{detail.goodsTypeName}</span></div>
                                    <div className={style.orderInfoGoodsUnitPrice}>
                                        <span className={style.unitPrice}>单价：￥{detail.goodsPrice}</span>
                                        <span className={style.unitPricePreference}>（优惠：-￥{detail.goodsDiscountAmount})</span>
                                    </div>
                                    <div className={style.buyNum}>数量：{detail.quantity}</div>
                                    <div className={style.totalPrice}>
                                        <span className={style.totalPriceTitle}>合计：</span>
                                        <span className={style.totalPriceValue}>￥{detail.tradeAmount}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </List>
                    {/* <List hidden={detail.cardType!=4} renderHeader={<span>账户信息</span>} className={style.accoutInfo}>
                        <ListItem title={<div className={style.payWayItem}><div className={style.info}> <div className={style.name}>充值账号：</div></div></div>}>
                            <div className={style.inputPhone}>
                                <input type="phone" maxLength={11}  placeholder="请输入充值账号" onChange={(e) => {
                                }} />
                            </div>
                        </ListItem>
                        <ListItem title={<div className={style.payWayItem}><div className={style.info}> <div className={style.name}>确认账号：</div></div></div>}>
                            <div className={style.inputPhone}>
                                <input type="phone" maxLength={11} placeholder="请再次输入充值账号" onChange={(e) => {
                                }} />
                            </div>
                        </ListItem>
                    </List> */}
                    <List renderHeader={<span>优惠信息</span>}>
                        <ListItem arrow={!redList.length || !noNeedPay ? '' : "right"} onClick={() => {
                            noNeedPay && redList.length && this.setState({ visible: true })
                        }} title={<div className={style.payWayItem}>
                            <img className={style.payWayIcon} src={icon_redpacket} />
                            <div className={style.info}>
                                <div className={style.name}>{!noNeedPay ? "红包抵扣" : "可用红包"}</div>
                                <div hidden={!noNeedPay} className={style.tips}>{!redList.length ? '暂无红包可用' : `${redList.length}个红包可用`}</div>
                            </div>
                        </div>}>
                            {!noNeedPay ?
                                <div className={style.deduction} ><span>{parseFloat(detail.couponAmount) ? ('- ￥' + detail.couponAmount) : '不使用'}</span></div>
                                : <div className={style.deduction} hidden={!redList.length}><span>{(redIndex != -1) && redList.length ? ('- ￥' + redList[redIndex].calculateActualAmount) : '不使用'}</span></div>}
                        </ListItem>
                        <ListItem title={<div className={style.payWayItem}>
                            <img className={style.payWayIcon} src={icon_coin} />
                            <div className={style.info}>
                                <div className={style.name}>嘿豆抵扣<span onClick={() => {
                                    Dialog.alert(<div style={{ textAlign: 'left' }}>
                                        1.低于{beanRule.minUse}嘿豆时不可使用抵扣。<br />
                                        2.抵扣比例为支付金额的{beanRule.proportion}%，嘿豆数量不足时，抵扣比例以嘿豆数量为准。<br />
                                        3.100嘿豆可抵1元。<br />
                                    </div>, '嘿豆使用规则')
                                }}></span></div>
                                <div className={style.tips} hidden={!noNeedPay}>共{allBeans}嘿豆，本次可使用{canUseBeans}嘿豆</div>
                            </div>
                        </div>}>
                            <div className={style.deduction} onClick={() => {
                                if (allBeans < beanRule.minUse) {
                                    Toast.info('嘿豆不足哦～');
                                } else if (noBeansMoney == '0.01') {
                                    Toast.info('该笔订单无法使用嘿豆');
                                }
                            }}>
                                {!noNeedPay ? <span>- ¥{detail.pointAmount}</span> : <span hidden={!canUseBeans || !hasDeduction}>- ￥{canUseBeans / 100}</span>}
                                <Switch hidden={!noNeedPay} value={hasDeduction && (noBeansMoney != '0.01')} disabled={!canUseBeans || (noBeansMoney == '0.01')} onChange={() => canUseBeans && this.setState({ hasDeduction: !hasDeduction })} />
                            </div>
                        </ListItem>
                    </List>
                    <List renderHeader={<span>支付方式</span>}>
                        <ListItem onClick={() => {
                            this.setState({
                                accountType: "WECHAT"
                            })
                        }} title={<div className={style.payWayItem}><img className={style.payWayIcon} src={icon_wechat} /><span>微信支付</span></div>}>
                            {
                                this.state.accountType == "WECHAT" && <Icon className={classnames("x-icon-check-circle", style.iconCheckCircle)} />
                            }
                        </ListItem>
                    </List>
                </div>
                <Popup maskStyle={{ background: 'rgba(0,0,0,.3)' }} mask={true} animation="bottom" offset={{ bottom: 0, left: 0, right: 0 }} visible={this.state.visible}>
                    <div className={style.redpacketPop}>
                        <div className={style.title}>可用红包<div className={style.close} onClick={() => {
                            this.setState({
                                visible: false
                            })
                        }}></div></div>
                        <div className={style.redList}>
                            {
                                redList.length ? redList.map((item, index) => {
                                    return <RedItem changeIndex={(selectIndex) => {
                                        this.setState({
                                            redIndex: selectIndex || index
                                        })
                                    }} selected={redIndex == index} item={item} key={index} />
                                }) : ''
                            }
                        </div>
                        <div className={style.sureRed}>
                            <div className={style.btn} onClick={() => {
                                this.setState({
                                    visible: false
                                })
                            }}>确定</div>
                        </div>
                    </div>
                </Popup>
                <div className={style.buyBar}>
                    <div className={style.buyButtons}>
                        <div className={style.priceAndTime}>
                            <div className={style.payPrice}>
                                <span className={style.payPriceTitle}>实际支付：</span>
                                <span className={style.payPriceValue}>¥ {!noNeedPay ? util.Sub(util.Sub(detail.tradeAmount, (detail.couponAmount || 0)), (detail.pointAmount || 0)) : neeDHaiDouMoney}</span>
                            </div>
                        </div>
                        <div className={style.toBuyAndTime}>
                            <div className={style.buyTime}>{this.state.buyTimeFormateText}</div>
                            <Button className={style.toBuy} onClick={() => {
                                Toast.loading("", 50000);
                                if (queryObject.purchase) {
                                    if (this.state.tradeNo) {
                                        this.payMoney(this.state.tradeNo, util.Sub(util.Sub(detail.tradeAmount, (detail.couponAmount || 0)), (detail.pointAmount || 0)));
                                        return;
                                    }
                                    purchase({
                                        tradeAmount: queryObject.purchase * detail.price,
                                        quantity: queryObject.purchase,
                                        origin: "H5",
                                        goodsType: tradeNo,//ID
                                        requestNo: util.uuid(),
                                        couponId: (redIndex != -1) && redList[redIndex] ? redList[redIndex].couponId : '',
                                        pointAmount: hasDeduction ? canUseBeans / 100 : 0
                                    }).then(ress => {
                                        pageDetail({
                                            tradeNo: ress.data
                                        }).then(res => {
                                            this.setState({
                                                detail: res.data,
                                                noNeedPay: false,
                                                tradeNo: ress.data
                                            }, () => {
                                                this.futureTime = new Date(this.state.detail.gmtCreated.replace(/-/g, "/")).getTime() + this.buyTime * 60 * 1000; // 固定的未来时间
                                                if (!!this.runBuyTime()) {
                                                    Dialog.alert("库存可能发生变动，请重新下单。", "订单超时", () => {
                                                        history.back();
                                                    })
                                                } else {
                                                    this.buyTimmer = setInterval(() => {
                                                        if (!!this.runBuyTime()) {
                                                            clearInterval(this.buyTimmer);
                                                            Dialog.alert("库存可能发生变动，请重新下单。", "订单超时", () => {
                                                                history.back();
                                                            })
                                                        }
                                                    }, 1000)
                                                }
                                            })
                                        }).then(() => {
                                            this.payMoney(ress.data, neeDHaiDouMoney);
                                        })

                                    })
                                } else {
                                    this.payMoney(tradeNo, neeDHaiDouMoney);
                                }

                            }}>立即支付</Button>
                        </div>
                    </div>
                </div>
            </Fragment>
        )
    }
}


class RedItem extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            item: props.item,
            active: false,//显示规则
            selected: props.selected
        }
    }


    componentWillReceiveProps(nextProps) {
        if (nextProps.selected != this.state.selected) {
            this.setState({
                selected: nextProps.selected
            })
        }
    }

    render() {
        let { item, active, selected } = this.state;
        let bgimg = 'normal';
        if (item.status == "UNUSED") {
            (item.cardType == 1) && (bgimg = 'discount');
        }
        return <div className={classnames(style.nouse, { [style.isNew]: !!item.isNew })}>
            <div className={classnames(style.bg, style[bgimg])}>
                <div className={style.discounts}>
                    <div className={style.redMoney}>
                        {item.cardType == 1 ? <span>{util.Mul(item.couponRatio, 10)}折</span> : <span><span className={style.currency}>¥</span>{item.amount}</span>}
                    </div>
                    <div className={style.useLimit}>{item.tips}</div>
                </div>
                <div className={style.redContent}>
                    <div className={style.mainInfo} onClick={() => {
                        this.props.changeIndex && this.props.changeIndex(selected ? -1 : '');
                    }}>
                        <div className={style.content}>
                            <div className={style.redTitle}>{item.cardName}</div>
                            <div className={style.useTime}>{util.dateFormat(new Date(item.useStartTime.replace(/\-/g, "/")), 'yyyy.MM.dd')} - {util.dateFormat(new Date(item.pastDueTime.replace(/\-/g, "/")), 'yyyy.MM.dd')}</div>
                        </div>
                        <Icon onClick={() => {
                            this.props.useBtn && this.props.useBtn(item)
                        }} className={classnames(selected ? "x-icon-check-circle" : "x-icon-circle-o", style.iconCheckCircle)} />
                    </div>
                    <div className={style.ruleTitle} onClick={() => {
                        this.setState({
                            active: !active
                        })
                    }}>使用规则
                <div className={classnames(style.down, { [style.up]: active })}></div>
                    </div>
                </div>
            </div>
            <div className={classnames(style.tips, { [style.active]: active })}>
                {
                    item.limitTypeDesc.map((item, index) => {
                        return <div key={index}>· {item}</div>
                    })
                }
                {
                    <div hidden={!item.firstOrderLimit}>· 限新人首单可用</div>
                }
                {
                    item.seckillLimit == 1 ? <div>· 秒杀商品不可用</div> : ''
                }
            </div>
        </div>
    }
}

export default App;